<?php

namespace App\Models;

use App\ModelFilters\Qh_CourseFilter;
use App\Service\Redis\RedisBaseService;
use DB;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Auth;
use Psr\SimpleCache\InvalidArgumentException;

class Qh_Course extends BaseModel
{
    protected $table = 'qh_courses';

    protected $guarded = [];

    protected $appends = ['userHas', 'learnPeopleCount', 'userLearnQuestionCount', 'questionLibraryAmount'];

    public function modelFilter(): ?string
    {
        return $this->provideFilter(Qh_CourseFilter::class);
    }

    public function questionLibrary(): BelongsTo
    {
        return $this->belongsTo(Qh_QuestionLibrary::class, 'qlId');
    }

    public function knowledge(): HasMany
    {
        return $this->hasMany(Qh_Knowledge::class, 'courseId');
    }

    /**
     * 题库价格
     * @return int|mixed
     */
    public function getQuestionLibraryAmountAttribute()
    {
        return 0;
        // if (!is_null($this->qlId)) return Qh_QuestionLibrary::find($this->qlId)->value('amount') ?? 0;
        // else return 0;
    }

    /**
     * 在学总数
     * @return int
     * @throws \RedisException
     * @throws InvalidArgumentException
     */
    public function getLearnPeopleCountAttribute(): int
    {
        return (new RedisBaseService())->getLearnUserCountInCourse($this->id);
    }

    /**
     * 当前用户已学的试题数量
     * @return int
     * @throws \RedisException
     */
    public function getUserLearnQuestionCountAttribute(): int
    {
        $count = 0;
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            $count = (new RedisBaseService())->getUserLearnQuestionCountByCourse($user->id, $this->id);
        }
        return $count;
    }

    /**
     * 用户是否拥有
     * @return bool
     * @throws \RedisException
     */
    public function getUserHasAttribute(): bool
    {
        if ($this->amount == 0) {
            return true;
        }else {
            if (Auth::guard('api')->check()) {
                $user = Auth::guard('api')->user();
                // 查询用户是否拥有了
                $hadIds = (new RedisBaseService())->getUserHadCourseIds($user->id);
                if (in_array($this->id, $hadIds)) return true;
            }
        }
        return false;
    }
}
